﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Admin.NET.Application.Entity;
using Microsoft.AspNetCore.Http;
using Furion.DatabaseAccessor;
namespace Admin.NET.Application;

/// <summary>
/// 采集照片服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class CaiJiPhotosService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<CaiJiPhotos> _caiJiPhotosRep;
    private readonly SqlSugarRepository<CaiJiLog> _caiJiLogRep;
    public CaiJiPhotosService(SqlSugarRepository<CaiJiPhotos> caiJiPhotosRep, SqlSugarRepository<CaiJiLog> caiJiLogRep)
    {
        _caiJiPhotosRep = caiJiPhotosRep;
        _caiJiLogRep = caiJiLogRep;
    }

    /// <summary>
    /// 分页查询采集照片
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    [DisplayName("分页查询采集照片")]
    public async Task<SqlSugarPagedList<CaiJiPhotosOutput>> Page(CaiJiPhotosInput input)
    {
        var query = _caiJiPhotosRep.AsQueryable()
            .WhereIF(input.EmployeeId>0, u => u.EmployeeId == input.EmployeeId)
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<Employee>((u, employeeid) => u.EmployeeId == employeeid.Id )
            .OrderBy(u => u.CreateTime)
            .Select((u, employeeid) => new CaiJiPhotosOutput
            {
                Id = u.Id,
                EmployeeId = u.EmployeeId, 
                EmployeeIdName = employeeid.Name,
                ClothesGroup = u.ClothesGroup,
                Direction = u.Direction,
                Photos = u.Photos,
                TenantId = u.TenantId,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input, "u.").ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加采集照片
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    [DisplayName("增加采集照片")]
    public async Task<long> Add(AddCaiJiPhotosInput input)
    {
        var entity = input.Adapt<CaiJiPhotos>();
        await _caiJiPhotosRep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 批量增加采集照片
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Adds")]
    [DisplayName("批量增加采集照片")]
    [UnitOfWork]
    public async Task<long> Adds(List<CaiJiPhotos> input)
    {

        //批量删除
        if (input.Count > 0) { 
            await _caiJiPhotosRep.DeleteAsync(u => u.EmployeeId == input[0].EmployeeId);
        }
        //保存图片
        foreach (var InputItem in input)
        {
            foreach (var item in InputItem.Photos)
            {
                var entity = await _caiJiLogRep.GetFirstAsync(u => u.Id.ToString() == item) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
                var path = Path.Combine(App.WebHostEnvironment.WebRootPath, $"images\\CaiJiPhotos\\{item}.jpg");
                //如果上面目录不存在，创建目录
                if (!Directory.Exists(Path.GetDirectoryName(path)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                }
                var bytes = Convert.FromBase64String(entity.ImageBase64);
                await File.WriteAllBytesAsync(path, bytes);
            }
        }

        foreach (var InputItem in input) {
            var entity = InputItem.Adapt<CaiJiPhotos>();
            await _caiJiPhotosRep.InsertAsync(entity);
        }
        return 0;
    }

    /// <summary>
    /// 删除采集照片
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    [DisplayName("删除采集照片")]
    public async Task Delete(DeleteCaiJiPhotosInput input)
    {
        var entity = await _caiJiPhotosRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _caiJiPhotosRep.FakeDeleteAsync(entity);   //假删除
        //await _caiJiPhotosRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新采集照片
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    [DisplayName("更新采集照片")]
    public async Task Update(UpdateCaiJiPhotosInput input)
    {
        var entity = input.Adapt<CaiJiPhotos>();
        await _caiJiPhotosRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取采集照片
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    [DisplayName("获取采集照片")]
    public async Task<CaiJiPhotos> Detail([FromQuery] QueryByIdCaiJiPhotosInput input)
    {
        return await _caiJiPhotosRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取采集照片列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    [DisplayName("获取采集照片列表")]
    public async Task<List<CaiJiPhotosOutput>> List([FromQuery] CaiJiPhotosInput input)
    {
        return await _caiJiPhotosRep.AsQueryable().Select<CaiJiPhotosOutput>().ToListAsync();
    }

    /// <summary>
    /// 获取人员编号列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "EmployeeEmployeeIdDropdown"), HttpGet]
    [DisplayName("获取人员编号列表")]
    public async Task<dynamic> EmployeeEmployeeIdDropdown()
    {
        return await _caiJiPhotosRep.Context.Queryable<Employee>()
                .Select(u => new
                {
                    Label = u.Name,
                    Value = u.Id
                }
                ).ToListAsync();
    }




}
